package com.shouhuobao.bhi.login;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.UserBean;
import com.collectplus.express.tools.TextWatcherExt;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import droid.frame.activity.title.TitleRes;
import droid.frame.ui.dialog.BaseDialog;
import droid.frame.utils.android.ImmUtils;
import droid.frame.utils.lang.Str;

/**
 * 登录界面
 *
 * @author coffee<br>
 *         2015-6-24下午3:07:28
 */
@SuppressLint("HandlerLeak")
public class LoginActivity extends BaseActivity2 implements OnClickListener {

    private BroadcastReceiver smsReceiver;
    private IntentFilter smsFilter;

    private EditText mMobileEdit, mCodeEdit;// 手机号验证码
    private TextView mGetCodeTextView; // 获取验证码
    private Button mSubmitButton;// 登录
    private CheckBox mCheckBox;// 是否同意服务条款

    private TextView mAudioCodeLayout;// 语音验证码-layout
    private String loginPhone;// 正在获取验证码的手机号

    private TextView mReadTv;
    private BaseDialog baseDialog = null;
    //    private boolean isNormalCode = true;//true获取普通验证码  false获取语音验证码
    private int clickCount = 1;

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(R.anim.in_bottom2top, 0);
        super.onCreate(savedInstanceState);
        registerSmsReceiver();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.login);
        super.findViewById();
        getAppTitle().setTitle(null, null, new TitleRes(R.drawable.login_close, new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }));
        setTitleBackground(R.color.app_layout_bg);
        mMobileEdit = (EditText) findViewById(R.id.login_mobile_edit);
        // mMobileEdit.setFilters(new InputFilter[] { new InputFilterExt(5) });
        mMobileEdit.addTextChangedListener(new droid.frame.view.TextWatcherExt(1) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 可以修改手机号, 但是必须等到30s以后才可以重新发送
                if (s.length() == 13 && recLen == 30) {
                    mGetCodeTextView.setEnabled(true);
                    setTextviewEnableStyle(mGetCodeTextView, true);
                } else {
                    mGetCodeTextView.setEnabled(false);
                    setTextviewEnableStyle(mGetCodeTextView, false);
                }
            }
        });
        mCodeEdit = (EditText) findViewById(R.id.login_code_edit);
        mCodeEdit.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() >= 4) {
                    mSubmitButton.setText("立即登录");
                    setButtonEnableStyle(mSubmitButton, true);
                } else {
                    setButtonEnableStyle(mSubmitButton, false);
                }
                if (!mCodeEdit.getText().toString().isEmpty()) {
                    mAudioCodeLayout.setVisibility(View.GONE);
                }
                // 输入完寄件码，自动验证
                if (s.length() == 4) {
                    loginVerify();
                }
            }
        });
        mGetCodeTextView = (TextView) findViewById(R.id.login_get_code);
        mSubmitButton = (Button) findViewById(R.id.login_submit);
        mCheckBox = (CheckBox) findViewById(R.id.login_read_checkbox);
        mAudioCodeLayout = (TextView) findViewById(R.id.login_audio_info);
        mAudioCodeLayout.setOnClickListener(this);
        mGetCodeTextView.setOnClickListener(this);
        mReadTv = (TextView) findViewById(R.id.login_read_tv);
        mReadTv.setOnClickListener(this);
        mSubmitButton.setOnClickListener(this);
        //
        setButtonEnableStyle(mSubmitButton, false);
        setTextviewEnableStyle(mGetCodeTextView, false);
        mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String mRead = mReadTv.getText().toString();
                SpannableString styledText = new SpannableString(mRead);
                if (!isChecked) {
                    mReadTv.setTextColor(Color.BLACK);
                    styledText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.app_font_2)), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else {
                    loginVerify();
                    mReadTv.setTextColor(getResources().getColor(R.color.parcel_list_brown));
                    styledText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.parcel_list_brown)), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                mReadTv.setText(styledText, TextView.BufferType.SPANNABLE);
            }
        });

    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //获取图片验证码
            //            case MsgID.get_login_image_code:
            //                cancelLoadingDialog();
            //                final AppResult<?> appResult = JSON.parser(msg.obj);
            //                runOnUiThread(new Runnable() {
            //                    @Override
            //                    public void run() {
            //                        if (appResult.isSuccess()) {
            //                            if (baseDialog == null || baseDialog.isShowing() == false) {
            //                                baseDialog = DialogMgr.getLoginCode(isNormalCode ? 0 : 1, (BaseActivity2) getContext(), (String) appResult.getResult(), loginPhone);
            //                            } else {
            //                                //刷新dialog中的图片
            //                                ((ImageView) baseDialog.findViewById(R.id.login_code_iv)).setImageBitmap(BitmapUtils.base64ToBitmap((String) appResult.getResult()));
            //                            }
            //                        } else {
            //                            showToast(appResult.getMessage());
            //                        }
            //                    }
            //                });
            //                return true;
            // 语音验证码
            case MsgID.send_SoundVerifyNum:
                cancelLoadingDialog();
                AppResult<?> result = JSON.parser(msg.obj);
                switch (result.getStatus()) {
                    case 1:
                        showToast("验证码将通过电话语音方式发送，请留意接听来电");
                        break;
                    case 0:
                    default:
                        showToast(result.getMessage());
                        break;
                }
                return true;
            // 发送验证码
            case MsgID.send_verifyNum:
                cancelLoadingDialog();
                result = JSON.parser(msg.obj);
                switch (result.getStatus()) {
                    case 1:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                countDownStart();
                            }
                        });
                        break;
                    case 0:
                    default:
                        showToast(result.getMessage());
                        break;
                }
                return true;
            // 确认验证码
            case MsgID.confirmVerifyNum:
                cancelLoadingDialog();
                AppResult<UserBean> loginResult = JSON.parser(msg.obj, UserBean.class);
                UserBean user = loginResult.getResult();
                // loginResult.setStatus(1);
                // user = new UserBean();
                // user.setId(28);
                // user.setPhone("15210788660");
                if (loginResult.isSuccess()) {
                    AppCache.setUser(user);
                    setResult(RESULT_OK);
                    finish();
                    // 登录成功访问一下index接口
                    AppHttp.getInstance().getAppConfig(getContext());
                } else {
                    showToast(loginResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 获取验证码
            case R.id.login_get_code:
                if (mMobileEdit.getText().length() == 13) {
                    //                    isNormalCode = true;
                    loginPhone = mMobileEdit.getText().toString().replace(" ", "");
                    //                    getImageCode(loginPhone);
                    showLoadingDialog(null);
                    if (clickCount > 2) {
                        AppHttp.getInstance().loginSMSVerifyNum(loginPhone, 1);
                    } else {
                        AppHttp.getInstance().loginSMSVerifyNum(loginPhone, null);
                    }
                } else {
                    showToast("手机号输入有误");
                }
                break;
            // 获取语音验证码
            case R.id.login_audio_info:
                if (mMobileEdit.getText().length() == 13) {
                    //                    isNormalCode = false;
                    loginPhone = mMobileEdit.getText().toString().replace(" ", "");
                    //                    getImageCode(loginPhone);
                    showLoadingDialog(null);
                    AppHttp.getInstance().loginSoundVerifyNum(loginPhone);
                } else {
                    showToast("手机号输入有误");
                }
                break;
            // 登录
            case R.id.login_submit:
                loginVerify();
                break;
            // 用户使用条款
            case R.id.login_read_tv:
                Intent i = new Intent(getContext(), WebViewActivity.class);
                i.putExtra("title", "用户使用条款");
                startActivity(i);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ImmUtils.show(getContext(), mMobileEdit);
            }
        }, 500);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private int recLen = 30;
    private boolean isStart;
    private Runnable runnable = new Runnable() {
        public void run() {
            if (recLen == 1) {
                mAudioCodeLayout.setVisibility(View.VISIBLE);
                isStart = false;
                recLen = 30;
                mGetCodeTextView.setEnabled(true);
                mGetCodeTextView.getPaint().setFlags(0);
                mGetCodeTextView.setText("再次发送");
                setTextviewEnableStyle(mGetCodeTextView, true);
            }

            if (recLen == 29) {
                clickCount++;
                showToast("短信验证码已发送");
            }
            if (isStart) {
                recLen--;
                setTextviewEnableStyle(mGetCodeTextView, false);
                mGetCodeTextView.getPaint().setFlags(0);
                mGetCodeTextView.setText(recLen + "秒后重新发送");
                getHandler().postDelayed(this, 1000);
            }
        }
    };

    /**
     * 登录验证
     */
    private void loginVerify() {
        String phone = mMobileEdit.getText().toString().replace(" ", "");
        if (Str.isEmpty(phone) || Str.isEmpty(mCodeEdit.getText().toString())) {
            showToast("请输入手机号，获取验证码");
            return;
        }
        if (mCheckBox.isChecked() == false) {
            showToast("请阅读并同意软件许可服务协议");
            return;
        }
        showLoadingDialog(null);
        String code = mCodeEdit.getText().toString();
        AppHttp.getInstance().confirmVerifyNum(phone, code);
    }

    private void countDownStart() {
        getHandler().postDelayed(runnable, 1000);
        isStart = true;
        mGetCodeTextView.setEnabled(false);
        mCodeEdit.requestFocus();
        InputMethodManager imm = (InputMethodManager) mCodeEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    public Handler smsHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                mCodeEdit.setText(msg.obj.toString());
            }
        }

        ;
    };

    private void registerSmsReceiver() {
        smsFilter = new IntentFilter();
        smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        smsFilter.setPriority(Integer.MAX_VALUE);
        smsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Object[] objs = (Object[]) intent.getExtras().get("pdus");
                for (Object obj : objs) {
                    byte[] pdu = (byte[]) obj;
                    SmsMessage sms = SmsMessage.createFromPdu(pdu);
                    String message = sms.getMessageBody();
                    String from = sms.getOriginatingAddress();
                    if (!TextUtils.isEmpty(from)) {
                        String code = patternCode(message);
                        if (!TextUtils.isEmpty(code)) {
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = code;
                            smsHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };
        registerReceiver(smsReceiver, smsFilter);
    }

    /**
     * @param @param  patternContent
     * @param @return
     * @return String
     * @throws
     * @Title: 匹配短信中间的6个数字（验证码等）
     * @Description: TODO()
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile("(?<!\\d)\\d{4}(?!\\d)");
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (baseDialog != null) {
            baseDialog.dismiss();
        }
        getHandler().removeCallbacks(runnable);
        unregisterReceiver(smsReceiver);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.out_top2bottom);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                finish();
                break;
        }
        return true;
    }

    /**
     * 登录按钮的点击和不可点击状态
     *
     * @param textView
     * @param enable
     */
    public void setTextviewEnableStyle(TextView textView, boolean enable) {
        int bottom = textView.getPaddingBottom();
        int top = textView.getPaddingTop();
        int right = textView.getPaddingRight();
        int left = textView.getPaddingLeft();
        if (enable) {
            textView.setBackgroundResource(R.drawable.login_shape);
            textView.setTextColor(Color.BLACK);
        } else {
            textView.setBackgroundResource(R.drawable.login_default_shape);
            textView.setTextColor(getResources().getColor(R.color.app_font_2));
        }
        textView.setPadding(left, top, right, bottom);
    }

    /**
     * 获取图片验证码
     */
    //    public void getImageCode(String loginPhone) {
    //        showLoadingDialog(null);
    //        //获取图片验证码
    //        AppHttp.getInstance().getLoginImageCode(loginPhone);
    //    }

    /**
     * 输入完成图片验证码后，请求短信接口
     */
    //    public void getSMSNumCode(int type, String imageCode) {
    //        Android.hideSoftInput(getContext());
    //        if (mMobileEdit.getText().length() == 13) {
    //            loginPhone = mMobileEdit.getText().toString().replace(" ", "");
    //            showLoadingDialog(null);
    //            if (type == 0) {
    //                if (clickCount > 2) {
    //                    AppHttp.getInstance().loginSMSVerifyNum(loginPhone, imageCode, "1");
    //                } else {
    //                    AppHttp.getInstance().loginSMSVerifyNum(loginPhone, imageCode, "");
    //                }
    //            } else {
    //                AppHttp.getInstance().loginSoundVerifyNum(mMobileEdit.getText().toString().replace(" ", ""), imageCode);
    //            }
    //        }
    //    }
}
